package cannot.backcontroller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cannot.pojo.Remark;
import cannot.pojo.Role;
import cannot.pojo.Tv;
import cannot.pojo.User;
import cannot.pojo.UserDetail;
import cannot.service.RoleService;
import cannot.service.UserDetailService;
import cannot.service.UserRoleService;
import cannot.service.UserService;
import cannot.shiro.ShiroUtil;

/**
 * 管理员--用户信息管理
 * @author Administrator
 *
 */
@Controller
public class UserAdminController {
	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	UserDetailService userDetailService;
	@Autowired
	UserRoleService userRoleService;

	@RequestMapping("admin_user_page")
	public String userPage(Model model){
		List<User> users = userService.list();
		for(User u:users){
			UserDetail userDetail= userDetailService.getByForeginKey(u.getId());
			u.setUserDetail(userDetail);
		}
		List<Role> roles = roleService.list();
		model.addAttribute("users", users);
		model.addAttribute("roles", roles);
		return "admin/rightContent/subUser";
	}
	
	//通过用户获得对应的角色信息
	@RequestMapping("roleper_getRole_byUser")
	@ResponseBody
	public Object getRoleByUser(Long id){
		User u = new User();
		u.setId(id);
		List<Role> roles = roleService.listRoles(u);
		return roles;
	}
	
	//更新用户的角色信息
	@RequestMapping("roleper_updateUserRole")
	@ResponseBody
	public Object updateUserRole(long userId,long[] roleId){
		User u = new User();
		u.setId(userId);
		userRoleService.setRoles(u, roleId);
		return null;
	}
	//给用户赋予角色
	@RequestMapping("setRole")
	@ResponseBody
	public String setRole(String id){
		//获取用户id
    	String userName =  ShiroUtil.getUserByPrincipal();
    	if(userName==null){
    		return "LOGIN";
    	}else{
    		Long uid = userService.getByName(userName).getId();
    		User u = new User();
    		u.setId(uid);
    		if(id.equals("Y")){
    			userRoleService.setRoles(u, new long[]{14});
    		}else{
    		}
    		return "SUCCESS";
    	}
		
	}
}
